package cn.hamster3.mc.plugin.core.bungee.util;

import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.config.Configuration;
import net.md_5.bungee.config.ConfigurationProvider;
import net.md_5.bungee.config.YamlConfiguration;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

@SuppressWarnings("unused")
public final class CoreBungeeCordUtils {
    private CoreBungeeCordUtils() {
    }

    @NotNull
    public static Configuration getConfig(@NotNull File file) {
        if (!file.exists()) {
            throw new IllegalArgumentException("文件不存在");
        }
        try {
            return ConfigurationProvider.getProvider(YamlConfiguration.class).load(file);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @NotNull
    public static Configuration getPluginConfig(@NotNull Plugin plugin) {
        File configFile = new File(plugin.getDataFolder(), "config.yml");
        if (!configFile.exists()) {
            return saveConfig(plugin);
        }
        try {
            return ConfigurationProvider.getProvider(YamlConfiguration.class).load(configFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @NotNull
    public static Configuration getPluginConfig(@NotNull Plugin plugin, @NotNull String filename) {
        File configFile = new File(plugin.getDataFolder(), filename);
        if (!configFile.exists()) {
            return saveConfig(plugin, filename);
        }
        try {
            return ConfigurationProvider.getProvider(YamlConfiguration.class).load(configFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @NotNull
    public static Configuration saveConfig(@NotNull Plugin plugin) {
        return saveConfig(plugin, "config.yml");
    }

    @NotNull
    public static Configuration saveConfig(@NotNull Plugin plugin, @NotNull String filename) {
        if (plugin.getDataFolder().mkdir()) {
            plugin.getLogger().info("已生成插件存档文件夹");
        }
        File configFile = new File(plugin.getDataFolder(), filename);
        try {
            try (InputStream stream = plugin.getResourceAsStream(filename)) {
                if (stream != null) {
                    Files.copy(stream, configFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
                }
            }
            return ConfigurationProvider.getProvider(YamlConfiguration.class).load(configFile);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
